/*
 * Copyright (c) 2011
 * UNPUBLISHED PROPRIETARY SOURCE CODE.
 */

package com.webservice;

import com.webservice.domain.ErrorResponse;
import com.webservice.enums.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Handles Exceptions that are not handled at the Application Controller level.
 * Applies the global exception handling policy for the application.
 * @author vkolodrevskiy
 */
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    private MappingJacksonJsonView jsonView = new MappingJacksonJsonView();

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        logger.error("Exception occured. ", ex);
        return new ModelAndView(jsonView, "error", new ErrorResponse(ErrorCode.UNHANDLED_EXCEPTION.getCode(), ErrorCode.UNHANDLED_EXCEPTION.getMessage() + " " + ex.getLocalizedMessage()));
	}
}
